package com.learning.netease.optimize.trx.orderservice.service;

import com.alibaba.fastjson.JSONObject;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * ClassName: MQService
 * Description:
 * Date: 2019/1/30 16:12 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Service
public class MQService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void setUp() {

        // 消息发送完毕后，则回调此方法 ack 代表发送是否成功
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {

                // ack 为true，代表MQ 已经准确收到消息
                if (!ack) {
                    return;
                }

                // 修改本地消息表的状态
                String sql = "update t_msg set msgStatus = 1 where msgId=?";
                String msgId = correlationData.getId();

            }
        });
    }


    /**
     * 发送MQ消息，接收回执。在回执中增加 orderId 信息
     *
     * @param orderInfo
     */
    public void sendMsg(JSONObject orderInfo) {
        rabbitTemplate.convertAndSend("createOrderExchange", "", orderInfo.toJSONString(),
                new CorrelationData(orderInfo.getString("orderId")));
    }
}
